package org.fxkj.cloud.uaa.service.security.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.fxkj.cloud.uaa.service.security.AuthenticationConstant;
import org.fxkj.cloud.uaa.service.security.model.token.JwtAuthenticationToken;
import org.fxkj.cloud.uaa.service.security.model.token.RawAccessJwtToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import java.io.IOException;

/**
 * <p>Description: token认证</p>
 *
 * @author Wei, Wu
 * @create 2024/10/17 16:34
 */
public class WAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public WAuthenticationFilter(AntPathRequestMatcher matcher) {
        super(matcher);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String token = request.getHeader(AuthenticationConstant.AUTHENTICATION);
        if (StringUtils.isEmpty(token)){
            throw new RuntimeException("token 不可为空");
        }
        RawAccessJwtToken rawAccessJwtToken = new RawAccessJwtToken(token);
        return getAuthenticationManager().authenticate(new JwtAuthenticationToken(rawAccessJwtToken));
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        SecurityContext context = SecurityContextHolder.createEmptyContext();
        context.setAuthentication(authResult);
        SecurityContextHolder.setContext(context);
        chain.doFilter(request, response);
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        super.unsuccessfulAuthentication(request, response, failed);
    }
}
